package handler

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"mxshop_srvs/goods_srv/global"
	"mxshop_srvs/goods_srv/model"
	"mxshop_srvs/goods_srv/proto"
)

func (svc *GoodsServer) BannerList(ctx context.Context, empty *emptypb.Empty) (*proto.BannerListResponse, error) {
	bannerListResponse := proto.BannerListResponse{}
	var banners []model.Banner
	//查询所有banner
	result := global.DB.Find(&banners)
	//1. 统计banner 数量
	bannerListResponse.Total = int32(result.RowsAffected)
	//2. 将banner 放入切片
	var bannerResp []*proto.BannerResponse
	for _, val := range banners {
		bannerResp = append(bannerResp, &proto.BannerResponse{
			Id:    val.ID,
			Image: val.Image,
			Index: val.Index,
			Url:   val.Url,
		})
	}
	//将切片里的数据存入bannerListResponse.Data
	bannerListResponse.Data = bannerResp
	return &bannerListResponse, nil
}

func (svc *GoodsServer) CreateBanner(ctx context.Context, request *proto.BannerRequest) (*proto.BannerResponse, error) {
	//1.检测banner是否存在 这里让后台管理员自己看,

	//2. 插入数据,并将数据返回给 banner
	banner := &model.Banner{
		Image: request.Image,
		Index: request.Index,
		Url:   request.Url,
	}
	global.DB.Save(banner)
	return &proto.BannerResponse{Id: banner.ID}, nil
}

func (svc *GoodsServer) DeleteBanner(ctx context.Context, request *proto.BannerRequest) (*emptypb.Empty, error) {
	//1.Delete 删除对应数据,如果删除成功则返回影响行数 根据影响行数判断是否删除成功
	if result := global.DB.Delete(&model.Banner{}, request.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.InvalidArgument, "轮播图片不存在!")
	}
	return &emptypb.Empty{}, nil
}

func (svc *GoodsServer) UpdateBanner(ctx context.Context, request *proto.BannerRequest) (*emptypb.Empty, error) {
	//1.检测是否存在该轮播
	banner := &model.Banner{}
	if result := global.DB.First(banner, request.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.InvalidArgument, "轮播图片不存在!")
	}
	//2.传入参数
	if request.Image != "" {
		banner.Image = request.Image
	}
	if request.Url != "" {
		banner.Url = request.Url
	}
	if request.Index != 0 {
		banner.Index = request.Index
	}
	global.DB.Save(banner)
	return &emptypb.Empty{}, nil
}
